package com.mh.web.controller.Common;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.mh.common.core.controller.BaseController;
import com.mh.common.core.domain.BaseResp;
import com.mh.common.utils.ExcelUtils;
import com.mh.community.domain.HjyCommunity;
import com.mh.community.domain.dto.HjyCommunityDTO;
import com.mh.community.domain.dto.HjyCommunityExcelDTO;
import com.mh.community.service.HjyCommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/exportExcel")
public class ExportExcelController extends BaseController {

    @Autowired
    private HjyCommunityService cs;

    //导出小区数据
    @GetMapping("/exportCommunityExcel")
    public BaseResp exportExcel(HjyCommunity comm, HttpServletResponse resp) {

        //BaseController中的分页方法,前端会传入pageNum+pageSize
        startPage();

        //调用Service层获取全部信息-->返回实体类对应DTO
        List<HjyCommunityDTO> commDTOs = cs.selectList(comm);

        //数据转换(DTO-->ExcelDTO)
        //实体类DTO转换为流-->转换为ExcelDTO对象流-->转换为ExcelDTO对象集合
        List<HjyCommunityExcelDTO> excelDTOs = commDTOs.stream().map(dto -> {
            //创建Excel导出数据存放DTO对象
            HjyCommunityExcelDTO excelDTO = new HjyCommunityExcelDTO();
            //DTO对象赋值
            excelDTO.setCommunityId(dto.getCommunityId());
            excelDTO.setCommunityName(dto.getCommunityName());
            excelDTO.setCommunityCode(dto.getCommunityCode());
            excelDTO.setCommunityProvinceName(dto.getCommunityProvinceName());
            excelDTO.setCommunityCityName(dto.getCommunityCityName());
            excelDTO.setCommunityTownName(dto.getCommunityTownName());
            excelDTO.setCreateTime(dto.getCreateTime());
            excelDTO.setRemark(dto.getRemark());
            //赋值后的DTO对象返回
            return excelDTO;
        }).collect(Collectors.toList());//集合转换为集合

        //调用自定义的Excel导出工具类(自带的类ExcelExportUtil)
        ExcelUtils.exportExcel(excelDTOs,HjyCommunityExcelDTO.class,"小区信息.xls",resp,
                                new ExportParams("小区信息列表","小区信息"));

        return BaseResp.success("小区信息导入Excel成功");
    }
}
